<template>
  <div class="map" id="map">
    <div class="map-content">
      <div class="echarts" id="echarts"></div>
    </div>
  </div>
</template>

<script>
import { getMapOption } from "./echartMap";
import { getMap } from "./maputils";
import chinaData from "../assets/data/china.json";
import jiangsuData from "../assets/data/jiangsu.json"
import * as echarts from "echarts";
import mapBg from '../assets/images/mapBg.png'
import lineTop1 from '../assets/images/lineTop1.png'
import lineTop2 from '../assets/images/lineTop2.png'
import lineTop3 from '../assets/images/lineTop3.png'
import lineTop4 from '../assets/images/lineTop4.png'
import lineTop5 from '../assets/images/lineTop5.png'

export default {
  data() {
    return {
      mapOption: [],
      mapName: "china",
      citylist: [{ 中国: "401200965" }],
      lastCity: [],
      chart: {},
      cityStack: [],
    };
  },
  mounted() {
    this.initEcharts();
  },
  methods: {
    initEcharts() {
      // 渐变层颜色
      const colorList = [
        "#8b5e70",
        "#81596d",
        "#78556a",
        "#6e5068",
        "#644c65",
        "#5b4762",
        "#51435f",
        "#483e5c",
        "#3e3a59",
        "#343557",
        "#2b3154",
        "#212c51",
      ];
      // 生成渐变图层
      const geoList = [];
      for (let i = 1; i <= colorList.length; i++) {
        const mapOption = {
          map: "china",
          aspectScale: 0.85,
          emphasis: {
            disabled: true,
          },
          z: 12 - i,
          layoutCenter: ["50%", `${i * 0.3 + 50}%`], //地图位置
          layoutSize: "100%",
          itemStyle: {
            normal: {
              areaColor: colorList[i - 1],
              borderWidth: 0,
            },
          },
        };
        if (i === colorList.length) {
          mapOption.itemStyle.normal.shadowColor = "rgba(0, 0, 0, 0.71)";
          mapOption.itemStyle.normal.shadowBlur = 100;
        }
        geoList.push(mapOption);
      }
      // 获取柱状图配置
      const lineSeriesData = this.getLineData();
      const option = {
        geo: [
          // 最外围发光边界
          {
            map: "china",
            aspectScale: 0.85,
            layoutCenter: ["50%", "50%"], //地图位置
            layoutSize: "100%",
            z: 12,
            emphasis: {
              disabled: true,
            },
            itemStyle: {
              normal: {
                borderColor: "rgb(180, 137, 81)",
                borderWidth: 8,
                shadowColor: "rgba(218, 163, 88, 0.4)",
                shadowBlur: 20,
              },
            },
          },
          // 最外层遮罩蒙版
          {
            map: "china",
            aspectScale: 0.85,
            layoutCenter: ["50%", "50%"], //地图位置
            layoutSize: "100%",
            z: 14,
            itemStyle: {
              normal: {
                areaColor: "rgba(106, 125, 171, 0.45)",
                borderWidth: 0,
              },
            },
            label: {
              show: true,
              color: "#fff",
              fontSize: 14,
            },
            tooltip: {
              
            }
          },
          // 内部蓝色边界
          {
            map: "china",
            aspectScale: 0.85,
            layoutCenter: ["50%", "50%"], //地图位置
            layoutSize: "100%",
            z: 12,
            emphasis: {
              disabled: true,
            },
            itemStyle: {
              normal: {
                areaColor: {
                  image: mapBg,
                },
                borderColor: "#8aa5db",
                borderWidth: 1,
              },
            },
          },
          ...geoList,
        ],
        series: [
          // 地图数据柱子
          ...lineSeriesData,
        ],
        graphic: {
          // 左上角操作按钮
          type: "text",
          x: 25,
          y: 25,
          style: {
            text: "返回",
            fill: "#333",
            font: 'bolder 1em "Microsoft YaHei", sans-serif',
            fontSize: 35,
          },
          // 返回按钮点击事件
          onclick: () => {
            console.log('fanhui')
            // 利用函数的作用域，可以直接拿上面的name来用
            // if (this.citylist.length <= 1) return;
            // this.lastCity = this.citylist[this.citylist.length - 2];
            // const name = Object.keys(this.lastCity)[0];
            // const [grahpName, graphJson] = getMap(name);
            // // 删除最后一个元素
            // this.citylist.pop();
            // // 很多操作重复了，你可以将公共部分抽离出来
            // option.geo.map = grahpName;
            // this.$echarts.registerMap(grahpName, graphJson);
            // this.chart.setOption(option, true);

            /**新方法 */
             if (this.cityStack.length <= 2) return;
            // 移除当前层级
            this.cityStack.pop();
            const lastLevel = this.cityStack[this.cityStack.length - 1];
            // 注册上一级地图
            echarts.registerMap(lastLevel.mapName, lastLevel.mapJson);
            // 更新地图配置
            option.geo.forEach(geoItem => {
              geoItem.map = lastLevel.mapName;
            });
            this.chart.clear();
            this.chart.setOption(option);
          },
        },
      };
      // 初始化DOM 获取容器
      this.chart = echarts.init(document.getElementById("echarts"));
      echarts.registerMap("china", chinaData);
      // this.mapOption = getMapOption();
      // chart.setOption(this.mapOption);
      this.chart.setOption(option);

      // 页面缩放
      window.addEventListener("resize", () => {
        this.chart.resize();
      });

      // 点击事件触发
      this.chart.on("click", (dom) => {
        console.log("dom====", dom);
        event.stopPropagation(); // 阻止冒泡
        const provincName = dom.name.replace(/(省|市|自治区|特别行政区)$/, "");
        // 重新获取地图数据并渲染
        const [mapName, mapJson] = getMap(provincName);
        if (mapJson) {
          // 记录当前层级信息
          this.cityStack.push({
            name: provincName,
            mapName,
            mapJson,
          });
          // 注册地图
          echarts.registerMap(mapName, mapJson);
          // 保证geo中的mapName与注册的地图名称一致
          option.geo.forEach(geoItem => {
            geoItem.map = mapName;
          });
          this.chart.clear();
          this.chart.setOption(option);

          if (!mapJson) return;

          // 是否暴露点击事件
          if (dom.seriesType == "scatter") return;

          const { name: cityName, data } = dom;
          const name = cityName || Object.keys(this.lastCity)[0];
          let code = "";
          if (dom.componentType === "series") {
            code = data?.areaUniCode ? data?.areaUniCode : this.lastCity[name];
          } else {
            code = this.lastCity[name];
          }
          this.lastCity.push({ [name]: code });
        }
      })
    },
    // 获取地图json数据， 默认中国地图
    async getMapJSON(geoName, adcode = 100000) {
      const res = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=${adcode}_full`);
      echarts.registerMap(geoName,  res.data);  // 重新注册地图
      const mapData = res.data.features.map((item) => {// 过滤json数据
        return {
          value: item.properties,
          name: item.properties.name,
        };
      });
      return mapData;
    },
    // 生成地图数据柱数据
    getLineData() {
      let lineTopList = [lineTop1, lineTop2, lineTop3, lineTop4, lineTop5]; 
      const districtData = [
        {
          name: "南京市",
          value: 267,
          point: [118.767413, 32.041544],
        },
        {
          name: "常州市",
          value: 200,
          point: [119.946973, 31.772752],
        },
        {
          name: "苏州市",
          value: 129,
          point: [120.619585, 31.299379],
        },
        {
          name: "扬州市",
          value: 107,
          point: [119.421003, 32.393159],
        },
        {
          name: "无锡市",
          value: 86,
          point: [120.301663, 31.574729],
        },
      ];
      const lineSeriesData = [];
      const maxValue = Math.max(...districtData.map((item) => item.value));
      districtData.forEach((item, index) => {
        // 柱子
        const lineData = {
          type: "lines",
          zlevel: 5,
          effect: {
            show: false,
            symbolSize: 5,
          },
          lineStyle: {
            width: 10,
            color: {
              type: "linear",
              x: 1,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: "rgba(232, 204, 149, 1)",
                },
                {
                  offset: 1,
                  color: "rgba(170, 144, 91, 1)",
                },
              ],
              global: false,
            },
            opacity: 1,
            curveness: 0,
          },
          label: {
            show: 0,
            position: "end",
            formatter: "245",
          },
          silent: true,
          data: [
            {
              ...item,
              coords: [
                item.point,
                [item.point[0], item.point[1] + item.value / maxValue],
              ],
            },
          ],
        };
        // 柱子顶部
        const lineTop = {
          type: "scatter",
          coordinateSystem: "geo",
          geoIndex: 0,
          zlevel: 5,
          label: {
            show: false,
          },
          symbol: "circle",
          symbolSize: [10, 5],
          itemStyle: {
            color: "rgba(255, 255, 179, 1)",
          },
          silent: true,
          data: [
            [item.point[0], item.point[1] + item.value / maxValue],
            [item.point[0], item.point[1] + item.value / maxValue],
          ],
        };
        // 柱子底部
        const lineBottom = {
          type: "scatter",
          coordinateSystem: "geo",
          geoIndex: 0,
          zlevel: 4,
          label: {
            show: false,
          },
          symbol: "circle",
          symbolSize: [10, 5],
          itemStyle: {
            color: {
              type: "linear",
              x: 1,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: "rgba(232, 204, 149, 1)",
                },
                {
                  offset: 1,
                  color: "rgba(170, 144, 91, 1)",
                },
              ],
              global: false,
            },
          },
          silent: true,
          data: [item.point],
        };
        // *****底部光圈*****
        const lineBottomCircle = {
          name: "Top 5",
          type: "effectScatter",
          coordinateSystem: "geo",
          data: [
            {
              name: item["name"],
              value: [item.point[0], item.point[1], item["value"]],
            },
          ],
          showEffectOn: "render",
          rippleEffect: {
            scale: 5,
            brushType: "stroke",
          },
          label: {
            normal: {
              formatter: "{b}",
              position: "bottom",
              show: false,
              color: "#fff",
              distance: 10,
            },
          },
          symbol: "circle",
          symbolSize: [20, 10],
          itemStyle: {
            normal: {
              color: "rgba(232, 204, 149, 1)",
              shadowBlur: 10,
              shadowColor: "rgba(232, 204, 149, 1)",
            },
            opacity: 1,
          },
          zlevel: 4,
        };
        // 顶部图标
        const lineTopIcon = {
          type: "scatter",
          coordinateSystem: "geo",
          geoIndex: 0,
          zlevel: 5,
          label: {
            normal: {
              show: true,
              formatter: function (params) {
                return `{cityName|${params.name}}\n {value|${params.data.data}} {unit|万人}`;
              },
              rich: {
                cityName: {
                  color: "rgba(201, 211, 234, 1)",
                  fontSize: 14,
                  padding: [6, 0, 4, 48],
                },
                value: {
                  color: "rgba(255, 187, 94, 1)",
                  fontSize: 18,
                  fontWeight: 800,
                  padding: [0, 0, 0, 44],
                },
                unit: {
                  color: "rgba(255, 187, 94, 1)",
                  fontSize: 14,
                },
              },
            },
            emphasis: {
              show: true,
            },
          },
          symbol: `image://` + lineTopList[index],
          symbolSize: [143, 48],
          symbolOffset: [0, 0],
          z: 999,
          data: [
            {
              name: item.name,
              data: item.value,
              value: [
                item.point[0],
                item.point[1] + item.value / maxValue + 0.2,
              ],
            },
          ],
        };
        lineSeriesData.push(lineData);
        lineSeriesData.push(lineTop);
        lineSeriesData.push(lineBottom);
        lineSeriesData.push(lineBottomCircle);
        lineSeriesData.push(lineTopIcon);
      });
      return lineSeriesData;
    },
    // 返回上一级地图
    goBack() {
      if(mapList.length >=2) {
        const { name, adcode } = mapList[mapList.lnegth -2];
        mapList.splice(-2, 2);
        this.getMapJSON({name, adcode}, (date) => {
          // 重新渲染地图
          this.initEcharts(name, data)
        })
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .map-content {
    position: relative;
    width: 1920px;
    height: 1080px;
  }

  .echarts {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
</style>
